# -*- coding: utf-8 -*-
# @Date    : 2017-05-23 21:54:45
# @Author  : fancy (fancy@thecover.co)
import time
import socket

def socker_server():
    ''' TCP server
    '''
    server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    host = '::1'
    port = 8001
    BUFSIZE = 1024
    server.bind((host, port))
    server.listen(5)

    try:
        while True:
            connect, addr = server.accept()
            print 'connection from ', addr
            while True:
                tmp = connect.recv(BUFSIZE)
                if not tmp:
                    break
                connect.send('%s [%s]' % (tmp, time.ctime()))
            connect.close()

        server.close()
    except Exception, e:
        print e
    finally:
        server.close()


def udp_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    host = ''
    port = 8888
    BUFSIZE = 1024
    server.bind((host, port))

    try:
        while True:
            data, addr = server.recvfrom(BUFSIZE)
            print 'get data from %s' % str(addr)
            server.sendto('[%s] %s' % (time.ctime(), data), addr)
    except Exception, e:
        print e
    finally:
        server.close()


if __name__ == '__main__':
    # socker_server()
    udp_server()
